package com.jingdianjichi.wx.handler.factory;

import com.jingdianjichi.wx.enums.WxChatMsgTypeEnum;
import com.jingdianjichi.wx.handler.WxChatMsgHandler;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信消息类型的工厂
 */
@Component
public class WxChatMsgFactory implements InitializingBean {

    @Resource
    private List<WxChatMsgHandler> wxChatMsgHandlerList;        //所有的实现类注入进来


    private Map<WxChatMsgTypeEnum,WxChatMsgHandler> handlerMap=new HashMap<>();

    //获得不同的处理器
    public WxChatMsgHandler getHandlerByMsgType(String msgType){
        WxChatMsgTypeEnum msgTypeEnum = WxChatMsgTypeEnum.getByMsgType(msgType);

        return handlerMap.get(msgTypeEnum);
    }


    //Spring的生命周期,填充工厂
    @Override
    public void afterPropertiesSet() throws Exception {
        for (WxChatMsgHandler wxChatMsgHandler : wxChatMsgHandlerList) {
            handlerMap.put(wxChatMsgHandler.getMsgType(),wxChatMsgHandler);
        }
    }
}
